package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.server.vo.SoundVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class SoundService {
    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private PicUploadService picUploadService;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;


    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //存储查询次数的key
    private static final String SCA_TIME = "USER_TIME_NO_";

    /**
     * 发送语音
     *
     * @param file 语音文件
     * @param
     * @return
     */
    public Boolean saveSound(MultipartFile file) {

        try {
            User user = UserThreadLocal.get();
           //创建对象
            Sound sound = new Sound();
            sound.setUserId(user.getId());//用户id
 //阿里云上传
//            PicUploadResult picUploadResult = picUploadService.upload(file);
//            sound.setSouUrl(picUploadResult.getName());//路径

            //上传视频到FastDFS中
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), //获取输入流
                    file.getSize(),  //获取长度
                    StrUtil.subAfter(file.getOriginalFilename(), '.', true),
                    null);
            //获取路径 并且拼接
            sound.setSouUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

            //调用dubbo层添加语音的方法
            String soundId = soundApi.saveSound(sound);
             //返回一个 不是空的
            return StrUtil.isNotEmpty(soundId);
        } catch (Exception e) {
            log.error("SoundService 层上传语音失败..." + e);
            e.printStackTrace();
        }

        return false;
    }


    /**
     * 接收语音 （不针对每个人，只针对语音）
     *
     * @return
     */
    public SoundVo querySound() {

        User user = UserThreadLocal.get();
          //获取Redis的值
        String numKey = redisTemplate.opsForValue().get(SCA_TIME + user.getId());
        //如果等于空就set
        if (numKey == null) {
            //设置    Redis key 并且设置过期时间
            redisTemplate.opsForValue().set(SCA_TIME + user.getId(), "10", Duration.ofSeconds(30));
        }

        //查询出所有存储在redis中的sid
        List<String> sidList = soundApi.querySidList();
        if (CollUtil.isEmpty(sidList)) {
            return null;
        }

        //生成一个随机数，长度就是里边装的sid集合的长度(用这个数作为查询sidList集合的索引)
        int randomNum = RandomUtils.nextInt(0, sidList.size() - 1);//最后一个为空

        //根据随机数生成的索引，在sidList集合中获取到对应的sid，根据sid去查询语音
        Sound sound = soundApi.querySound(Convert.toLong(sidList.get(randomNum)));
                                          //根据id查询user对象
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(sound.getUserId());
//      查询Redis剩余次数    USER_TIME_NO_
        String num = redisTemplate.opsForValue().get(SCA_TIME + user.getId());

        SoundVo soundVo = new SoundVo();

        if (Convert.toInt(num) > 0) {
            soundVo.setId(sound.getUserId());
            soundVo.setAvatar(userInfo.getLogo());
            soundVo.setNickname(userInfo.getNickName());
            soundVo.setGender(userInfo.getSex().name().toLowerCase());
            soundVo.setSoundUrl(sound.getSouUrl());
            soundVo.setAge(userInfo.getAge());
            soundVo.setRemainingTimes(Convert.toInt(num));//剩余次数

            //每获取到一个语音，获取语音的次数就要-1
            redisTemplate.opsForValue().set(SCA_TIME + user.getId(), String.valueOf(Convert.toInt(num) - 1), Duration.ofSeconds(30));
        } else {
            soundVo = new SoundVo();
            soundVo.setRemainingTimes(0);
        }

        return soundVo;

    }
}
